﻿function JqueryAjax(url, mtype, senddata, callback, dataType, contentType) {
    try {

        if (contentType == null || contentType == undefined) {
            contentType = "application/json";
        }
        if (dataType == null || dataType == undefined) {
            dataType = "json";
        }
        asyncfalg = false;
        if (callback == undefined || callback == null) {
            asyncfalg = false;
        }
        else {
            asyncfalg = true;
        }


        if (contentType.indexOf("json") >= 0) {
            senddata = JSON.stringify(senddata);
        }
        responsetext = $.ajax({
            url: url,
            type: mtype,
            dataType: dataType,
            contentType: contentType,            
            headers: Headers,
            cache: false,
            async: asyncfalg,
            data: senddata,
            success: function (ResData) {
                if (!asyncfalg) {
                    return ResData;
                }
                else {
                    callback(ResData);
                }
            },
            error: function (ResData) {
                if (!asyncfalg) {
                    return ResData.responseText;
                }
                else {
                    callback(ResData.responseText, ResData.status, ResData);
                }
            },
            complete: function (XHR, TS) {
                //alert(XHR.responseText);
                try {
                    if (dataType == "json") {
                        return eval("(" + XHR.responseText + ")");
                    }
                }
                catch (e) {
                    if (XHR.responseURL != undefined) {
                        window.location = XHR.responseURL;
                    }
                    else {
                        document.body.innerHTML = XHR.responseText;
                    }
                }
            }
        });
        if (!asyncfalg) {
            try {
                if (contentType.indexOf("json") >= 0) {
                    return eval("(" + responsetext.responseText + ")");
                }
                else {
                    if (responsetext.responseURL != undefined) {
                        window.location = responsetext.responseURL;
                    }
                    else {
                        return responsetext.responseText;
                    }
                }
            }
            catch (e) {
                if (responsetext.responseURL != undefined) {
                    window.location = responsetext.responseURL;
                }
                else {
                    document.body.innerHTML = responsetext.responseText;
                }
                //return responsetext.responseText;
            }
        }
        //return eval("(" + responsetext.responseText + ")");
    }
    catch (e) {
        alert(e.message);
        return null;
    }
}

function getQuery(name) {
    ScrStr = window.location.search.substr(1);
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = ScrStr.match(reg);
    if (r != null) return unescape(r[2]); return null;
}

Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

function GetDataStr(data, fmt) {
    var jsdate = new Date(data);// eval('new ' + eval(data).source);
    return jsdate.Format(fmt);
}

function escape2Html(str) {
    var arrEntities = { 'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"' };
    return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all, t) { return arrEntities[t]; });
}

function HTMLDecode(text) {
    var temp = document.createElement("div");
    temp.innerHTML = text;
    var output = temp.innerText || temp.textContent;
    temp = null;
    return output;
}

function SetPopPicker(obj, itemArray, modyfiUrl) {
    var userPicker = new mui.PopPicker();


    if (modyfiUrl != null && modyfiUrl != undefined && modyfiUrl != "") {
        userPicker.cancel.innerText = "编辑";
        userPicker.cancel.addEventListener('tap', function (event) {
            location.href = modyfiUrl;
        }, false);
    }
    obj.addEventListener('tap', function (event) {
        userPicker.setData(itemArray);
        userPicker.show(function (items) {
            obj.value = items[0].text;
            obj.key = items[0].value;
            return true;
        });
    }, false);
}

function SetDatePicker(obj, dateformat) {
    obj.addEventListener('tap', function () {
        var optionsJson = dateformat || '{}';
        var options = JSON.parse(optionsJson);
        var id = obj.getAttribute('id');

        var picker = new mui.DtPicker(options);
        picker.show(function (rs) {


            obj.value = rs.text;
            picker.dispose();
        });


    }, false);
}


//验证手机号合法性
function checkPhone(tel) {
    var phone = tel;
    if (!(/^1[34578]\d{9}$/.test(phone))) {
        return false;
    }
    else {
        return true;
    }
}

function checkinput(classname) {
    if (classname == undefined) {
        classname = "required";
    }
    var List = document.getElementsByClassName(classname);
    for (var i = 0; i < List.length; i++) {
        if (List[i].nextElementSibling.children[0].value == "") {
            TipMessage("请输入" + List[i].outerText);
            List[i].nextElementSibling.children[0].focus();
            return false;
        }
    }
    return true;
}

function checkinputM(classname) {
    if (classname == undefined) {
        classname = "required";
    }
    var List = document.getElementsByClassName(classname);
    for (var i = 0; i < List.length; i++) {
        if (List[i].children[1].value == "") {
            List[i].getElementsByClassName("help-text")[0].innerHTML = "请输入" + List[i].children[1].placeholder;
            List[i].children[1].focus();
            return false;
        }
    }
    return true;
}

function SelectSubTreeNode(ZTree, PNode, IdList, index, CallBack) {
    if (PNode.isAjaxing) {
        window.setTimeout(function () { SelectSubTreeNode(ZTree, PNode, IdList, index, CallBack) }, 100);
    }
    else {
        index = index + 1;
        if (index < IdList.length) {
            var SubNode = ZTree.getNodeByParam("id", IdList[index], PNode);
            if (SubNode == null)
                return false;
            if (SubNode.isParent) {
                ZTree.expandNode(SubNode, true, false, true, true);
                SelectSubTreeNode(ZTree, SubNode, IdList, index, CallBack);
            }
            else {
                ZTree.selectNode(SubNode);
                if (CallBack != undefined && CallBack != null) {
                    CallBack(SubNode);
                }
            }
        }
        else {
            ZTree.selectNode(SubNode);
            if (CallBack != undefined && CallBack != null) {
                CallBack(SubNode);
            }
        }
    }
}

//展开指定的节点
function SelectZTreeNode(ZTree, IdList, CallBack, key) {
    var Node;
    if (key == undefined) {
        Node = ZTree.getNodeByParam("id", IdList[0], null);
    }
    else {
        Node = ZTree.getNodeByParam(key, IdList[0], null);
    }
    if (Node == null) {
        return false;
    }
    if (Node.isParent) {
        ZTree.expandNode(Node, true, false, false, true);
        if (Node.isAjaxing) {
            window.setTimeout(function () { SelectSubTreeNode(ZTree, Node, IdList, 0, CallBack) }, 100);
            return;
        }
        else {
            SelectSubTreeNode(ZTree, Node, IdList, 0, CallBack);
        }
        return;
    }
    else {
        ZTree.selectNode(Node);
        if (CallBack != undefined && CallBack != null) {
            CallBack(Node);
        }
    }
    return;
}

function TipMessage(msg, type, actions, callback, time, icon, placement) {
    new $.messager.show(msg, {
        type: (type == undefined ? "info" : type),
        icon: (icon == undefined ? "info" : icon),
        time: (time == undefined ? 2000 : time),
        actions: (actions == undefined ? [] : actions),
        onAction: (callback == undefined ? null : callback),
        placement: (placement == undefined ? "bottom" : placement) // 定义显示位置
    });

    //$.messager.show(msg, { type: 'success', placement: 'bottom', displayAuto: true });

}

function webSocket(recvEvent) {
    this.ws = new WebSocket('ws://' + window.location.hostname + ':' + window.location.port + '/WebHandle/WebSocketHandler.ashx');
    this.ws.onopen = function () {
        //$('#tips').text('已经连接');
        //alert(1);
    };
    this.ws.onmessage = function (evt) {
        if (recvEvent != undefined) {
            recvEvent(JSON.stringify(evt));
        }
    };
    this.ws.onerror = function (evt) {
        //alert(0);

        //$('#tips').text(JSON.stringify(evt));
    };
    this.ws.onclose = function () {
        //alert(-1);
        //$('#tips').text('已经关闭');
    };
}
webSocket.prototype.sendData = function (data) {

    if (this.ws.readyState == WebSocket.OPEN) {
        this.ws.send(data);
    }
    else {
        return -1;
    }
};

var addModal = null;

function ShowDilag(url, caption, h, w, o, call, type) {
    options = {
        iframe: url,
        height: h,
        width: w,
        title: caption,
        keyboard: true,
        moveable: true,
        backdrop: 'static',
        type: type
    };
    if (addModal != null) {
        $('#triggerModal').on('hidden.zui.modal', function () {
            return ShowDilag(url, caption, h, w, o, call, type);
        });
        addModal.close();
        return false;
    }
    if (o != undefined) {
        window.dialogArguments = o;
    }
    if (type == undefined || type == null) {
        type = "custom";
    }

    addModal = new $.zui.ModalTrigger(options);
    window.dilag = addModal;
    addModal.show({
        onHide: function () {
            if (call != null && call != undefined) {
                call();
            }
            addModal = null;
        }
    });
    return false;
}



function getNextInput(input) {
    inputList = $('input');
    for (var i = 0; i < inputList.length; i++) {
        if (input == inputList[i]) {
            if (i < inputList.length - 1) {
                return inputList[i + 1];
            }
            else {
                return input;
            }
        }
    }

}

function Divonkeypress() {
    if (event != null) {
        if (event.keyCode == 13) {
            var element = event.srcElement || event.target;
            if (document.all) {
                event.keyCode = 9;
            } else {
                if (element.type != "button" && element.type != "submit") {
                    col = getNextInput(element);
                    if (col.type != "submit" && element != col) {
                        event.preventDefault();
                    }
                    col.focus();

                }
            }
        }
    }
}


$(function () {
    $('a').on('click', function (a) {
        if (this.target == "_blank") {

            ShowDilag(this.href, this.getAttribute("caption"), this.getAttribute("height"),
                this.getAttribute("width"), this.getAttribute("obj"), call);
            return false;
            //这个是重要的，其实这种方式很多时候都会用到，只是在这里不容易想到而已；
        }
    });
    $('input').on('keypress', function (a) {
        Divonkeypress();
    });

});
